using System;
using Magiq.Behaviors;
using Magiq.Insert;
using Magiq.Objects;
using Magiq.Support;

namespace Magiq.Databases.Insert
{
    public class DatabaseInsertStrategy<TSource, TDestination, TNew> : BehaviorHandler<IDatabaseInsertBehavior<TSource, TDestination, TNew>>, IInsertStrategy, IDatabaseBasedExecution where TDestination : class where TNew : class
    {
        public DatabaseInsertStrategy(IDatabaseAdapter databaseAdapter, IInsert<TSource, TDestination, TNew> insert)
            : base(insert.Behavior)
        {
            DatabaseAdapter = databaseAdapter;
            this.insert = insert;
            Default<DatabaseInsertBehavior<TSource, TDestination, TNew>>();
        }

        private readonly IInsert<TSource, TDestination, TNew> insert;

        public IDatabaseAdapter DatabaseAdapter { get; private set; }

        public int Execute()
        {
            Call(x => x.Initialize(DatabaseAdapter, insert));
            var inserts = Call(x => x.BuildDatabaseInserts());
            var result = 0;
            foreach (var insert in inserts)
            {
                var command = Call(x => x.BuildCommand(insert));
                result += command.ExecuteNonQuerySafe();
            }
            return result;
        }
    }
}